<template>
	<view>
		<view class="u-demo-block__content" style="margin: 15rpx;">
			<view class="u-page__tag-item">
				<u-search placeholder="输入合同号、物料名称或规格模糊查询" 
				v-model="contractCode" 
				@custom="queryContractList"
				@search="queryContractList"></u-search>
			</view>
		</view>
		<view>
			<u-tabs
				@click="tabClick"
				:list="tabList"
				:current="currentTabIndex"
				lineWidth="58"
				lineColor="#f56c6c"
				:activeStyle="{
					color: '#303133',
					fontWeight: 'bold',
					transform: 'scale(1.05)'
				}"
				:inactiveStyle="{
					color: '#606266',
					transform: 'scale(1)'
				}"
				itemStyle="padding-left: 15px; padding-right: 15px; height: 40px;">
			</u-tabs>
		</view>
		<view v-if="currentTabIndex === 0">
			<view class="card-container" v-if="contractList.length > 0">
				<uni-segmented-control :current="current" :values="tabItems" style-type="button"
								inActiveColor="#ffffff" active-color="#3c9cff" @clickItem="onClickItem">
				</uni-segmented-control>
				<!-- 每一个折叠卡片的事件在这里 -->
				<uni-collapse accordion v-model="multiCollaspe" @change="changeDetail">
					<view v-for="(item, index) in contractList"
					class="card-wrap"
					:key="index"
					:class="{ 'card-wrap-selected': item.selectedCard === 1 }"
					@click="selectCard(item)">
						<view class="card-item" v-if="groupType != 'contractCode'">
							工单号：
							<u--text :text="item.workerorderCode" type="info"></u--text>
						</view>
						<view class="card-item">
							订单合同：
							<u--text :text="item.contractCode" style="color: aquamarine;"></u--text>
						</view>
						<view class="card-item">
							产地：
							<u--text :text="sliceFName(item.factoryName)" type="info"></u--text>
							班组：
							<u--text :text="item.teamName" bgColor="#e3e4e6"></u--text>
						</view>
						<view class="card-item" v-if="groupType == 'contractCode'">
							最小业务状态：
							<u--text :text="item.kingStatusDesc" style="color: #62c188;"></u--text>
						</view>
						<view class="card-item" v-else>
							业务状态：
							<u--text :type="buildType(item.kingStatus)" :text="item.kingStatusDesc" style="color: #62c188;"></u--text>
						</view>
						<view class="card-item">
							产品规格(首行)：
							<u--text :text="item.bomName" type="info"></u--text>
							<u--text :text="item.bomStandard" type="info"></u--text>
						</view>
						<view class="card-item">
							<u--text type="primary" prefixIcon="/static/submit/number.png" size="16" 
							:text="`订单总数: ${item.workorderNum}`"></u--text>
							<u--text color="#1ee684"  prefixIcon="/static/submit/finished.png" size="16" 
							:text="`累计完工数: ${item.hasCompletionNum?item.hasCompletionNum:0}`"></u--text>
						</view>
						
						<view class="card-item" v-if="item.workorderNum != item.hasCompletionNum">
							<u-button text="开始报工" size="normal" type="primary" @click="goToReport(item)"></u-button>
						</view>
						<view class="card-item" v-else>
							<u-button text="查看报工详情" size="normal" type="primary" @click="goToReport(item)"></u-button>
						</view>
					</view>
				</uni-collapse>
			</view>
			<view v-if="contractList.length == 0" style="padding-top: 60px;">
				<u-loading-icon text="数据加载中" textSize="18" color="#19be6b" :show="loadingShow"></u-loading-icon>
				<u-empty mode="data" v-if="!loadingShow"></u-empty>
			</view>
		</view>
		<view v-if="currentTabIndex === 1">
			<view class="card-container" v-if="finishedList.length > 0">
			<uni-collapse accordion v-model="finishedCollaspe">
				<view v-for="(item, index) in finishedList"
				class="card-wrap"
				:key="index"
				:class="{ 'card-wrap-selected': item.selectedCard === 1 }"
				@click="selectCard(item)">
					<view class="card-item" v-if="groupType != 'contractCode'">
						工单号：
						<u--text :text="item.workerorderCode" type="info"></u--text>
					</view>
					<view class="card-item">
						订单合同：
						<u--text :text="item.contractCode" style="color: aquamarine;"></u--text>
					</view>
					<view class="card-item">
						产地：
						<u--text :text="sliceFName(item.factoryName)" type="info"></u--text>
						班组：
						<u--text :text="item.teamName" bgColor="#e3e4e6"></u--text>
					</view>
					<view class="card-item">
						最小业务状态：
						<u--text :type="buildType(item.kingStatus)" :text="item.kingStatusDesc" style="color: aquamarine;"></u--text>
					</view>
					<view class="card-item">
						产品规格(首行)：
						<u--text :text="item.bomName" type="info"></u--text>
						<u--text :text="item.bomStandard" type="info"></u--text>
					</view>
					<view class="card-item">
						<u--text type="primary" prefixIcon="/static/submit/number.png" size="16" 
						:text="`订单总数: ${item.workorderNum}`"></u--text>
						<u--text color="#1ee684"  prefixIcon="/static/submit/finished.png" size="16" 
						:text="`累计完工数: ${item.hasCompletionNum?item.hasCompletionNum:0}`"></u--text>
					</view>
					
					<view class="card-item">
						<u-button text="查看报工详情" size="normal" type="primary" @click="goToReport(item)"></u-button>
					</view>
				</view>
				</uni-collapse>
			</view>
			<view v-if="finishedList.length == 0" style="padding-top: 60px;">
				<u-loading-icon text="数据加载中" textSize="18" color="#19be6b" :show="finishedLoadingShow"></u-loading-icon>
				<u-empty mode="data" v-if="!finishedLoadingShow"></u-empty>
			</view>
		</view>
		<view v-if="currentTabIndex === 2">
			<view class="u-demo-block__content" style="margin: 16rpx; display: flex; align-items: center;">
					<text style="margin-right: 7rpx;">报工日期：</text>
				<view class="u-page__tag-item" style="flex: 1;">
					<uni-datetime-picker 
						  v-model="submitDateRange" 
						  type="daterange" 
						  @change="dateRangeClick" />
				</view>
			</view>
			<view v-if="contractHistoryList.length > 0">
			
				<uni-collapse accordion v-model="multiCollaspeHistory" @change="changeDetailHistory">
				<uni-collapse-item 
					thumb="/static/submit/submit_history.png" 
					:title="item.mainText" 
					v-for="(item, index) in contractHistoryList" :key="index" >
					<view style="margin: 5px;">
						<uni-table ref="table" :loading="detailLoading"
							border
							stripe 
							type="" 
							emptyText="暂无更多数据">
						<uni-tr style="background-color: #dbfbdb;">
							<uni-th align="left" width="5" style="font-size: 12px;color: #62c188;">序号</uni-th>
							<uni-th align="left" width="100" style="font-size: 12px;color: #62c188;">报工日期</uni-th>
							<uni-th align="left" width="100" style="font-size: 12px;color: #62c188;">合同号</uni-th>
							<uni-th align="left" width="100" style="font-size: 12px;color: #62c188;">产品名称</uni-th>
							<uni-th align="left" width="70" style="font-size: 12px;color: #62c188;">产品规格</uni-th>
							<uni-th align="left" width="60" style="font-size: 12px;color: #62c188;">订单数量</uni-th>
							<uni-th align="left" width="60" style="font-size: 12px;color: #62c188;">当天累计合格数量</uni-th>
							<uni-th align="left" width="60" style="font-size: 12px;color: #62c188;">当天累计不良品数量</uni-th>
							<uni-th align="left" width="60" style="font-size: 12px;color: #62c188;">累计完工数量</uni-th>
							<uni-th align="left" width="60" style="font-size: 12px;color: #62c188;">还欠数量</uni-th>
							<uni-th align="left" width="50" style="font-size: 12px;color: #62c188;">产品编码</uni-th>
							<uni-th align="left" width="50" style="font-size: 12px;color: #62c188;">站点名称</uni-th>
							<uni-th align="left" width="50" style="font-size: 12px;color: #62c188;">报工人</uni-th>
							<uni-th align="left" style="font-size: 12px;color: #62c188;">当天备注</uni-th>
						</uni-tr>
						<uni-tr v-for="(productItem, subIndex) in contractHistoryDetailList" :key="subIndex">
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ subIndex+1 }}</uni-td>
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ productItem.submitDate }}</uni-td>
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ productItem.contractCode }}</uni-td>
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ productItem.bomName }}</uni-td>
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ productItem.bomStandard }}</uni-td>
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ productItem.workorderNum }}</uni-td>
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ productItem.goodNum }}</uni-td>
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ productItem.ungoodNum }}</uni-td>
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ productItem.hasCompletionNum }}</uni-td>
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ productItem.remainingCompletionNum }}</uni-td>
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ productItem.bomCode }}</uni-td>
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ productItem.stationName }}</uni-td>
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ productItem.creator }}</uni-td>
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ productItem.remark }}
						</uni-td>
						</uni-tr>
						</uni-table>
					</view>
				</uni-collapse-item>
				</uni-collapse>
			</view>
			<view v-else style="padding-top: 60px;">
				<u-loading-icon text="数据加载中" textSize="18" color="#19be6b" :show="loadingShow"></u-loading-icon>
				<u-empty mode="data" v-if="!loadingShow"></u-empty>
			</view>
		</view>
		
		
		<u-toast ref="uToast" duration="3000" />
		<uni-fab ref="fab"
			:pattern="pattern" 
			:content="content" 
			:horizontal="horizontal" 
			:vertical="vertical"
			:direction="direction" 
			@trigger="trigger" 
			@fabClick="fabClick" />
			
		<u-loadmore :status="loadStatus" />
	</view>
</template>

<script>
const d = new Date();
const year = d.getFullYear();
let month = d.getMonth() + 1;
month = month < 10 ? `0${month}` : month;
const date = d.getDate();

import FloatMuitlButton from '@/components/button/FloatMuitlButton';
import SumitInfo from '@/components/definedialog/submitInfo';
import StationOptions from '@/components/definedialog/stationOptions';
import * as submitApi from '@/api/work/worksubmit';
import storage from '@/utils/storage';

export default {
	components: {
		FloatMuitlButton,
		SumitInfo,
		StationOptions,
	},
	data() {
		return {
			// 悬浮按钮开始
			pattern: {
				color: '#7A7E83',
				backgroundColor: '#fff',
				selectedColor: '#007AFF',
				buttonColor: '#007AFF',
				iconColor: '#fff',
				icon: 'gear'
			},
			tabItems: ['合并视图', '分解视图'],
			styleType: 'button',
			current: 0,
			activeColor: '#007aff',
			groupType: 'contractCode',
			
			// submitShowDate: false,
			// submitMinDate: `${year}-${month}-${date-3}`,
			// submitDefaultDate: `${year}-${month}-${date}`,
			
			content: [{
					iconPath: '/static/picking/refresh.png',
					selectedIconPath: '/static/picked/refresh.png',
					text: '刷新当前',
					active: false
				},{
					iconPath: '/static/picking/history.png',
					selectedIconPath: '/static/picking/history_selected.png',
					text: '历史报工',
					active: false
				},
				// {
				// 	iconPath: '/static/picking/submit.png',
				// 	selectedIconPath: '/static/picking/submit_selected.png',
				// 	text: '提交报工',
				// 	active: false
				// }
			],
			horizontal: 'left',
			vertical: 'bottom',
			direction: 'vertical',
			// 悬浮按钮结束
			
			workOrderList: [],
			completionWorkList: [],
			
			contractList: [],
			finishedList: [],
			finishedCollaspe: "",
			
			contractHistoryList: [],
			contractHistoryDetailList: [],
			multiCollaspeHistory: "",
			
			loadingShow: false,
			finishedLoadingShow: false,
			submitInfoShow: false,
			
			submitTotal: 0,
			submitUngoodTotal: 0,
			tabList: [{
				name: '待报工',
			},{
				name: '已完成报工',
			},{
				name: '历史报工',
			}],
			show: false,
			// 查询参数，比如：合同号
			contractCode: "",
			submitDateList: [],
			checked: ["选中"],
			// u-checkbox-group的v-model绑定的值如果设置为某个checkbox的name，就会被默认选中
			checkboxValue1: [],
			selectedCard: null, // 选中的卡片ID
			trueValue: true,
			// 日期弹窗
			showDate: false,
			minDate: `${year}-${month}-${date-30}`,
			// defaultDateMultiple: [],
			
			submitDateRange: [],
			
			stationOptionShow: false,
			stationBtnText: "选择站点",
			
			isVisible: true,
			clickCount: 0,
			
			queryDateBtnText: "择查询日期",
			detailLoading: false,
			multiCollaspe: "",
			
			currentTabIndex: 0,
			currentSelectedList: [],
			
			currentCollapseIndex: null,
			
			loadStatus: "loadmore",
			total: 0,
			pageNum: 1,
			totalPageCount: 0,
			
			station: null,
		}
	},
	onLoad (options) {
		// TODO 临时测试数据
		// this.defaultDateMultiple.push(`${year}-${month}-${date-1}`);
		// this.defaultDateMultiple.push(`${year}-${month}-${date}`);
		this.submitDateRange.push(Date.now() - 2*24*3600*1000);
		this.submitDateRange.push(Date.now() + 2);
		
		this.queryContractList();
	},
	created() {
		console.log("tabIndex", this.currentTabIndex);
	},
	methods: {
		sliceFName(factoryName) {
			return factoryName ? factoryName.slice(0,2) : '-';
		},
		buildType(kingStatus) {
			if (kingStatus == '6' || kingStatus == '7') {
				return 'error';
			}
			return 'info';
		},
		onClickItem(e) {
			if (this.current !== e.currentIndex) {
				this.current = e.currentIndex
			}
			if (this.current == 0) {
				this.groupType = 'contractCode';
			} else if (this.current == 1) {
				this.groupType = 'contractCode_workCode';
			}
			this.queryContractList();
		},
		goToReport(item) {
			const contractCode = encodeURIComponent(item.contractCode);
			const workerorderCode = encodeURIComponent(item.workerorderCode);
			const url = `/pages/work/dayreport/worksubmitDetailB?factoryId=${item.factoryId}&teamId=${item.teamId}&contractCode=${contractCode}&workerorderCode=${workerorderCode}&groupType=${this.groupType}`;
			console.log("开始报工地址:", url);
			uni.navigateTo({ url: url });
		},
		onReachBottom() {
			if (this.currentTabIndex === 2) {
				return;
			} else if (this.currentTabIndex === 1) {
				console.log("onReachBottom", this.pageNum, this.totalPageCount);
				if (this.pageNum > this.totalPageCount
					|| this.finishedList.length === this.total) {
					console.log("已经加载到最多了");
					return;
				}
				this.pageNum ++;
				this.queryFinishedList();
				return;
			}
			console.log("onReachBottom", this.pageNum, this.totalPageCount);
			if (this.pageNum > this.totalPageCount 
				|| this.contractList.length === this.total) {
				console.log("已经加载到最多了");
				return;
			}
			this.pageNum ++;
			this.queryWaitingCompletionGroup();
		},
		dateRangeClick(e) {
			console.log('dateRangeClick:', e);
			if (e && e.length === 0) {
				this.submitDateRange = [];
			}
			this.queryContractList();
		},
		fabClick() {
		},
		todayRecvNumChange(productItem, e) {
			if (!productItem.todayCompletionReq) {
				return;
			}
			if (!(!isNaN(parseFloat(productItem.todayCompletionReq)) && isFinite(productItem.todayCompletionReq)) 
				|| productItem.todayCompletionReq <= 0) {
				this.$refs.uToast.error(`输入必须是大于 0 的数字`);
				return;
			}
			if (Number(productItem.todayCompletionReq) > productItem.remainingCompletionNum) {
				this.$refs.uToast.error(`${productItem.bomName}, 规格：${productItem.bomStandard} 最多还剩数量:${productItem.remainingCompletionNum} 未报工,请确认`);
				productItem.todayCompletionReq = productItem.remainingCompletionNum;
			}
		},
		ungoodNumReqChange(productItem, e) {
			if (!productItem.ungoodNumReq) {
				return;
			}
			
			if (!(!isNaN(parseFloat(productItem.ungoodNumReq)) && isFinite(productItem.ungoodNumReq)) 
				|| productItem.ungoodNumReq <= 0) {
				this.$refs.uToast.error(`输入必须是大于 0 的数字`);
				return;
			}
			if (Number(productItem.ungoodNumReq) >= productItem.workorderNum) {
				this.$refs.uToast.error(`输入不良品不可能比订单总数还多`);
				productItem.ungoodNumReq = null;
			}
		},
		clearRecvNum(row, e) {
			console.log("row->", row);
		},
		changeDetail(e) {
			console.log("e原始参数>>", e);
			if (!e) {
				return;
			}
			const index = Number(e);
			const proItem = this.contractList[index];
			if (proItem && proItem.contractCode) {
				this.queryWaitingCompletionList(proItem);
			}
		},
		changeDetailHistory(e) {
			console.log("历史e原始参数>>", e);
			if (!e) {
				return;
			}
			const index = Number(e);
			const proItem = this.contractHistoryList[index];
			if (proItem && proItem.submitDate) {
				this.queryContractHistoryDetail(proItem);
			}
		},
		handleLeftClick() {
		 this.floatOnclick();
		},
		handleRightClick() {
		 this.submitCompletion();
		},
		stationOptionUpdate() {
			console.log("stationOptionShow:", this.stationOptionShow);
			this.stationOptionShow = true;
		},
		saveStationOption(station) {
			console.log("saveStationOption:", station);
			// 缓存10天
			storage.set('STATION_0', station, 864000);
			this.stationBtnText = `站点(${station.stationName})`;
			this.stationOptionShow = false;
			this.station = station;
			this.queryContractList();
		},
		queryWaitingCompletionGroup() {
			this.loadingShow = true;
			
			submitApi.getWaitingCompletionGroupContract({
				// stationId: this.station.stationId,
				groupType: this.groupType,
				pageNum: this.pageNum,
				searchParam: this.contractCode,
				scene: "UNFINISHED",
			}).then(res => {
				console.log("查询待报工的订单数据成功:", res);
				if(res && res.rows) {
					const result = res.rows || [];
					for (let item of result) {
						this.contractList.push(item);
					}
				}
				this.loadingShow = false;
				
				// 分页查询
				this.totalPageCount = res.totalPageCount || 0;
				this.total = res.total || 0;
				if (this.pageNum >= this.totalPageCount 
					|| this.contractList.length === this.total) {
					this.loadStatus = 'nomore';
				} else {
					this.loadStatus = 'loading';
				}
				
				if (this.multiCollaspe == "") {
					return;
				}
				if (this.multiCollaspe
					&& this.multiCollaspe >= 0 
					&& this.contractList.length > this.multiCollaspe) {
					const cur = this.contractList[this.multiCollaspe];
					if (cur) {
						this.queryWaitingCompletionList(cur);
					}
				}
			}).catch(err => {
				console.error("查询待报工的订单数据异常:", err);
				this.loadingShow = false;
			});
		},
		// TODO 连接后台服务
		queryWaitingCompletionList(contract) {
			this.loadingShow = true;
			this.workOrderList = [];
			submitApi.getWaitingCompletionList({
				pageNum: 1,
				pageSize: 200,
				// stationId: this.station.stationId,
				contractCode: contract.contractCode,
			}).then(res => {
				console.log("查询待报工的订单数据成功:", res);
				if(res && res.rows) {
					this.workOrderList = res.rows || [];
				}
				let totalQty = 0;
				for (let obj of this.workOrderList) {
					totalQty += obj.hasCompletionNum ? obj.hasCompletionNum : 0;
				}
				if (contract.hasCompletionNum < totalQty) {
					contract.hasCompletionNum = totalQty;
				}
				this.loadingShow = false;
			}).catch(err => {
				console.error("查询待报工的订单数据异常:", err);
				this.loadingShow = false;
			});
		},
		queryHasCompletionList() {
			this.loadingShow = true;
			this.workOrderList = [];
			submitApi.getCompletionList({
				pageNum: 1,
				pageSize: 200,
				// stationId: this.station.stationId,
				contractCode: this.contractCode, 
				submitDateList: this.submitDateList,
			}).then(res => {
				console.log("查询已报工的订单数据成功:", res);
				if(res && res.rows) {
					this.workOrderList = res.rows || [];
				}
				this.loadingShow = false;
			}).catch(err => {
				console.error("查询已报工的订单数据异常:", err);
				this.loadingShow = false;
			});
		},
		queryContractHistory() {
			this.loadingShow = true;
			this.contractHistoryList = [];
			let startDate = null;
			let endDate = null;
			if (this.submitDateRange && this.submitDateRange.length >= 1) {
				startDate = this.formatDateString(this.submitDateRange[0]);
			}
			if (this.submitDateRange && this.submitDateRange.length >= 2) {
				endDate = this.formatDateString(this.submitDateRange[1]);
			}
			submitApi.querySubmitHistoryList({
				// stationId: this.station.stationId,
				contractCode: this.contractCode, 
				startDate: startDate,
				endDate: endDate,
			}).then(res => {
				console.log("查询已报工的历史记录成功:", res);
				if(res && res.rows) {
					this.contractHistoryList = res.rows || [];
				}
				this.loadingShow = false;
				this.loadStatus = 'nomore';
			}).catch(err => {
				console.error("查询已报工的历史记录异常:", err);
				this.loadingShow = false;
				this.loadStatus = 'nomore';
			});
		},
		queryContractHistoryDetail(proItem) {
			this.loadingShow = true;
			this.contractHistoryDetailList = [];
			const submitDates = [proItem.submitDate];
			submitApi.querySubmitHistoryBySubmitDate({
				pageNum: 1,
				pageSize: 300,
				factoryId: proItem.factoryId,
				teamId: proItem.teamId,
				// stationId: this.station.stationId,
				contractCode: this.contractCode, 
				submitDateList: submitDates,
			}).then(res => {
				console.log("查询已报工的历史记录详情成功:", res);
				if(res && res.rows) {
					this.contractHistoryDetailList = res.rows || [];
				}
				this.loadingShow = false;
			}).catch(err => {
				console.error("查询已报工的历史记录详情异常:", err);
				this.loadingShow = false;
			});
		},
		queryContractList() {
			this.pageNum = 1;
			if (this.currentTabIndex === 2) {
				// if (!this.pickedDateRange || this.pickedDateRange.length != 2) {
				// 	this.$refs.uToast.error(`请先选择记录日期，再进行查询`);
				// 	return;
				// }
				this.queryContractHistory();
				return;
			}
			this.contractList = [];
			this.customQuery();
		},
		queryFinishedList() {
			this.finishedLoadingShow = true;
			submitApi.getWaitingCompletionGroupContract({
				pageNum: this.pageNum,
				searchParam: this.contractCode,
				scene: "FINISHED",
			}).then(res => {
				console.log("查询已完工报工的订单数据成功:", res);
				if(res && res.rows) {
					const result = res.rows || [];
					for (let item of result) {
						this.finishedList.push(item);
					}
				}
				this.finishedLoadingShow = false;
				
				// 分页查询
				this.totalPageCount = res.totalPageCount || 0;
				this.total = res.total || 0;
				if (this.pageNum >= this.totalPageCount 
					|| this.finishedList.length === this.total) {
					this.loadStatus = 'nomore';
				} else {
					this.loadStatus = 'loading';
				}
			}).catch(err => {
				console.error("查询已完工报工的订单数据异常:", err);
				this.finishedLoadingShow = false;
			});
		},
		customQuery() {
			if(this.currentTabIndex === 0) {
				this.queryWaitingCompletionGroup();
			} else if (this.currentTabIndex === 1) {
				this.pageNum = 1;
				this.finishedList = [];
				this.queryFinishedList();
			} else if (this.currentTabIndex === 2) {
				this.queryContractHistory();
			}
		},
		tabClick(e) {
			console.log("tabClick,currentTabIndex", e, this.currentTabIndex);
			const preIndex = this.currentTabIndex;
			this.currentTabIndex = e.index;
			if (preIndex != e.index) {
				if (this.currentTabIndex === 0) {
					this.queryContractList();
				} else if(this.currentTabIndex === 1) {
					this.pageNum = 1;
					this.finishedList = [];
					this.queryFinishedList();
				} else if(this.currentTabIndex === 2) {
					this.queryContractHistory();
				}
				this.loadStatus = "nomore";
			}
		},
		// tabSlotClick(item) {
		// 	console.log('item', item);
		// 	if (this.queryDateBtnText === "清空查询日期") {
		// 		this.queryDateBtnText = "择查询日期";
		// 		this.submitDateList = [];
		// 		this.defaultDateMultiple = [];
		// 		this.queryContractHistory();
		// 		return;
		// 	}
		// 	this.showDate = true;
		// },
		selectCard(work) {
			// console.log("work=", work);
		},
		floatOnclick(e) {
			// TODO 扫描按钮事件
			console.log("扫描按钮事件:", e);
			// alert("正在打开飞书摄像头扫码");
			let _this = this;
			window.h5sdk.ready(() => {
				tt.scanCode({
					scanType: ["barCode", "qrCode", "datamatrix", "pdf417"],
					barCodeInput: true,
					success(res) {
						console.log("扫描返回:", res);
						// alert("成功:"+JSON.stringify(res));
						_this.contractCode = res.result;
						_this.customQuery();
					},
					fail(res) {
						console.log(`scanCode fail:`, res);
						alert("失败:"+JSON.stringify(res));
					},
				});
			});
		},
		// calendarConfirm(selectedItem) {
		// 	console.log("日历选中", selectedItem);
		// 	this.submitDateList = selectedItem;
		// 	this.showDate = false;
		// 	this.defaultDateMultiple = selectedItem;
		// 	this.queryDateBtnText = "清空查询日期";
		// 	this.customQuery();
		// },
		// calendarClose() {
		// 	this.showDate = false;
		// },
		open() {
			// console.log('open');
			document.body.style.overflow = 'hidden'; // 禁用背景页面滚动
		},
		close() {
			this.show = false
			// console.log('close');
			document.body.style.overflow = ''; // 恢复背景页面滚动
		},
		reset() {
		},
		trigger(e) {
			console.log("flowButton.e, multiCollaspe", e, this.multiCollaspe);
			const btn = this.content[e.index];
			btn.active = true;
			if (btn.text === '刷新当前') {
				
				this.partRefreshBomList();
				btn.active = false;
				
			} else if (btn.text === '历史报工') {
				
				this.loadStatus = 'nomore';
				this.currentTabIndex = 2;
				this.queryContractHistory();
				
			} else if (btn.text === '提交报工') {
				
				this.submitCompletion();
			}
		},
		partRefreshBomList() {
			if (this.currentTabIndex === 0) {
				console.log("multiCollaspe=", this.multiCollaspe);
				if (this.multiCollaspe == "") {
					console.log("collapse is blank");
					this.queryWaitingCompletionGroup();
					return;
				}
				if (this.multiCollaspe
					&& this.multiCollaspe >= 0 
					&& this.contractList.length > this.multiCollaspe) {
					const cur = this.contractList[this.multiCollaspe];
					if (cur) {
						this.queryWaitingCompletionList(cur);
					}
				}
			} else if (this.currentTabIndex === 1) {
				this.pageNum = 1;
				this.finishedList = [];
				this.queryFinishedList();
			} else {
				this.queryContractHistory();
			}
		},
		submitCompletion() {
			if (!this.workOrderList || this.workOrderList.length == 0) {
				this.$refs.uToast.error(`报工工单数据为空，提交失败`);
				return;
			}
			// 开始计算进行提交数据是否存在异常
			this.completionWorkList = [];
			let total = 0;
			let unGoodTotal = 0;
			for(let item of this.workOrderList) {
				if (!item.todayCompletionReq && Number(item.todayCompletionReq) <= 0
					&& !item.ungoodNumReq && Number(item.ungoodNumReq) <= 0) {
					continue;
				}
				this.completionWorkList.push({
					contractCode: item.contractCode,
					bomName: item.bomName,
					bomStandard: item.bomStandard,
					workerorderCode: item.workerorderCode,
					bomCode: item.bomCode,
					todayCompletionReq: item.todayCompletionReq,
					ungoodNumReq: item.ungoodNumReq,
					remark: item.remark,
				});
				total += Number(item.todayCompletionReq);
				unGoodTotal += Number(item.ungoodNumReq);
			}
			if (this.completionWorkList.length == 0) {
				this.$refs.uToast.error(`今日报工数都是 0，请先输入`);
				return;
			}
			
			this.submitInfoShow = true;
			this.submitTotal = total;//  合格产品
			this.submitUngoodTotal = unGoodTotal;// 不良品
		},
		submitReally(callItem) {
			this.submitInfoShow = false;
			for(let item of this.completionWorkList) {
				item.stationId = callItem.stationId;
				item.stationName = callItem.stationName;
				if (callItem.errMessage) {
					if (item.remark) {
						item.remark = item.remark + "," + callItem.errMessage;
					} else {
						item.remark = callItem.errMessage;
					}
				}
			}
			console.log("报工真正提交:", this.completionWorkList);
			submitApi.newSubmitStationDay(this.completionWorkList).then(res => {
				// 提交结果
				console.log("报工真正提交成功",  res);
				if (res.code == 200) {
					this.$refs.uToast.success(`今日报工提交成功,完工数:${this.submitTotal}`);
					// this.completionWorkList = [];
					// this.queryContractList();
					this.partRefreshBomList();
				} else {
					this.$refs.uToast.error(`今日报工提交失败,${res.msg}`);
				}
			}).catch(err => {
				// 提交异常
				console.error("报工真正提交发生异常", err);
			});
		},
		goToPre() {
			console.log("返回主页");
			uni.reLaunch({ url: '/pages/work/index' });
		},
		formatDateString(timestamp) {
			// 将长整型时间戳转换为毫秒
			const date = new Date(timestamp);
			// 获取年份、月份和日期
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以加1
			const day = String(date.getDate()).padStart(2, '0');
		
			// 返回格式化的日期字符串
			return `${year}-${month}-${day}`;
		},
	}
}
</script>

<style lang="scss" scoped>
/deep/.u-cell__body {
  // padding: 6px 0 !important;
  display: flex;
  flex-direction: row;
  box-sizing: border-box;
  padding: 6px 8px !important;
  font-size: 15px;
  color: #303133;
  align-items: center;
}
.card-container{
	width: 100%;
	min-height: 100%;
	box-sizing: border-box;
	padding: 10rpx;
	background-color: #ECECEC;
}
.card-wrap{
	padding: 12rpx;
	border-radius: 12rpx;
	margin-bottom: 12rpx;
	background-color: #FFF;
	border: 1px solid #ddd; /* 默认边框 */
	transition: background-color 0.3s, border-color 0.3s;
	.card-item{
		display: flex;
		align-items: center;
		font-size: 28rpx;
		padding-left: 6rpx;
		padding-bottom: 18rpx;
		color: #40485d;
	}
	.card-item-txt{
		flex:1;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
}
.card-btns{
	display: flex;
	justify-content: space-between;
	align-items: center;
}
.card-btns uni-button {
  flex: 1;
  margin: 0 5px; /* 调整按钮间距 */
}
.card-wrap-selected {
  border-color: #007bff; /* 选中状态的边框颜色 */
  background-color: #e7f0ff; /* 选中状态的背景颜色 */
}
.gridcell {
  border: 1px solid #ddd;
  text-align: center;
  line-height: 20px; /* Adjust line-height to match height */
  height: 30px; /* Set height to 20px */
  background-color: #f9f9f9;
  font-size: 14px; /* Adjust font-size to fit */
  overflow: hidden; /* Hide overflow if text is too large */
}
.card-item-single{
	border-radius: 6rpx;
	background-color: #FFF;
	border: 1px solid #ddd; /* 默认边框 */
	transition: background-color 0.3s, border-color 0.3s;
	align-items: left;
	font-size: 30rpx;
	color: #40485d;
}

.submit {
	// background-color: #007cff;
	text-align: center;
	margin: 5px 15px 5px 5px;
}

.demo-layout {
	height: 25px;
	border-radius: 4px;
}
.bg-purple {
	background: #CED7E1;
}
.bg-purple-light {
	background: #e5e9f2;
}


.flex-item {
	width: 33.3%;
	height: 200rpx;
	text-align: center;
	line-height: 200rpx;
}

.flex-item-V {
	width: 100%;
	height: 150rpx;
	text-align: center;
	line-height: 150rpx;
}

.text {
	margin: 15rpx 10rpx;
	padding: 0 20rpx;
	background-color: #ebebeb;
	height: 70rpx;
	line-height: 70rpx;
	text-align: center;
	color: #777;
	font-size: 26rpx;
}

.desc {
	/* text-indent: 40rpx; */
}
.flex-pc {
	display: flex;
	justify-content: center;
}

</style>
